package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.text.AutofitTextView;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerMaintainDetailComponent;
import com.chcit.mobile.di.module.MaintainDetailModule;
import com.chcit.mobile.mvp.contract.MaintainDetailContract;
import com.chcit.mobile.mvp.model.entity.MaintainBean;
import com.chcit.mobile.mvp.model.entity.Statu;
import com.chcit.mobile.mvp.presenter.MaintainDetailPresenter;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class MaintainDetailFragment extends ScanFragment<MaintainDetailPresenter> implements MaintainDetailContract.View {

    @BindView(R.id.tiet_maintain_detail_ConservationQty)
    TextInputEditText tvConservationQty;
    @BindView(R.id.til_maintain_detail_ConservationQty)
    TextInputLayout tilConservationQty;
    @BindView(R.id.spinner_maintain_detail_CheckResult)
    MaterialSpinner spinnerCheckResult;
    @BindView(R.id.spinner_maintain_detail_ConservationMeasure)
    MaterialSpinner spinnerConservationMeasure;
    @BindView(R.id.spinner_maintain_detail_QAState)
    MaterialSpinner spinnerQAState;
    @BindView(R.id.spinner_maintain_detail_Recommendations)
    MaterialSpinner spinnerRecommendations;
    @BindView(R.id.til_maintain_detail_CheckQty)
    TextInputLayout tilCheckQty;
    @BindView(R.id.tiet_maintain_detail_CheckQty)
    TextInputEditText tvCheckQty;
    @BindView(R.id.til_maintain_detail_ConservationDate)
    TextInputLayout tilConservationDate;
    @BindView(R.id.tiet_maintain_detail_ConservationDate)
    TextInputEditText tvConservationDate;
    @BindView(R.id.spinner_maintain_detail_CheckUser)
    MaterialSpinner spinnerCheckUser;
    @BindView(R.id.til_maintain_detail_QtyScrapped)
    TextInputLayout tilQtyScrapped;
    @BindView(R.id.tiet_maintain_detail_QtyScrapped)
    TextInputEditText tvQtyScrapped;
    @BindView(R.id.spinner_maintain_detail_ScrappedCheckResult)
    MaterialSpinner spinnerScrappedCheckResult;
    @BindView(R.id.spinner_maintain_detail_ScrappedConservationMeasure)
    MaterialSpinner spinnerScrappedConservationMeasure;
    @BindView(R.id.spinner_maintain_detail_ScrappedQAState)
    MaterialSpinner spinnerScrappedQAState;
    @BindView(R.id.spinner_maintain_detail_ScrappedRecommendations)
    MaterialSpinner spinnerScrappedRecommendations;
    @BindView(R.id.tv_maintain_detail_Description)
    AppCompatEditText tvDescription;
    @BindView(R.id.bt_maintain_detail_supervise)
    Button btMaintainDetailSupervise;
    @BindView(R.id.bt_maintain_detail_ok)
    Button btMaintainDetailOk;
    private int count;//必输字段数量
    private MaintainBean mMaintainBean;

    public static MaintainDetailFragment newInstance(MaintainBean maintainBean) {
        MaintainDetailFragment fragment = new MaintainDetailFragment();
        fragment.mMaintainBean = maintainBean;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMaintainDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .maintainDetailModule(new MaintainDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_maintain_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitle("养护记录填写");
        mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
            pop();
        });
        initShowData();
        initSpinner();
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    private void initShowData() {

        tvConservationQty.setText(String.valueOf(mMaintainBean.getConservationQty()));


    }

    private void initSpinner() {
        /*id:1000216
        检查结果
    */

        mPresenter.querySpinnerData(1000216, list -> {

            spinnerCheckResult.setItems(list);
            spinnerScrappedCheckResult.setItems(list);
            spinnerScrappedCheckResult.setSelectedIndex(list.size() - 1);

        });

        mPresenter.querySpinnerData(1000215, list -> {
            spinnerConservationMeasure.setItems(list);
            spinnerScrappedConservationMeasure.setItems(list);
            spinnerScrappedConservationMeasure.setSelectedIndex(list.size() - 1);

        });

        mPresenter.querySpinnerData(1000069, list -> {
            spinnerQAState.setItems(list);
            spinnerScrappedQAState.setItems(list);
            spinnerScrappedQAState.setSelectedIndex(list.size() - 1);

        });

        mPresenter.querySpinnerData(1000217, list -> {
            spinnerRecommendations.setItems(list);
            spinnerScrappedRecommendations.setItems(list);
            spinnerScrappedRecommendations.setSelectedIndex(list.size() - 1);
        });

        mPresenter.querySpinnerData(1000071, list -> {
            spinnerCheckUser.setItems(list);

        });


    }

    private void initEvent() {
        tvCheckQty.addTextChangedListener(new MyTextWatcher(tilCheckQty, "检查数量不能为空"));
        tvConservationDate.addTextChangedListener(new MyTextWatcher(tilConservationDate, "养护日期不能为空"));
        tvConservationQty.addTextChangedListener(new MyTextWatcher(tilConservationQty, "养护数量不能为空"));
        tvQtyScrapped.addTextChangedListener(new MyTextWatcher(tilQtyScrapped, "不合格数量不能为空"));

    }

    @OnClick({R.id.bt_maintain_detail_supervise, R.id.bt_maintain_detail_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_maintain_detail_supervise:
                pop();
                break;
            case R.id.bt_maintain_detail_ok:
                /*
                conservationAction/fill.do
                M_Conservation_ID:1000817
                ConservationQty:240
                ConservationMeasure:03
                CheckResult:1
                QAState:01
                Recommendations:1
                ConservationDate:2018-11-09T00:00:00
                CheckQty:240
                CheckUser:1000443
                QtyScrapped:0
                ScrappedCheckResult:1
                ScrappedConservationMeasure:
                ScrappedQAState:
                ScrappedRecommendations:
                Description:
                */
                JSONObject data = new JSONObject();
                data.put("M_Conservation_ID", mMaintainBean.getM_Conservation_ID());
                data.put("ConservationQty", tvConservationQty.getText());
                data.put("ConservationMeasure", spinnerConservationMeasure.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("CheckResult", spinnerCheckResult.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("QAState", spinnerConservationMeasure.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("Recommendations", spinnerRecommendations.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("ConservationDate", tvConservationDate.getText());
                data.put("CheckQty", tvCheckQty.getText());
                data.put("CheckUser", spinnerCheckUser.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("QtyScrapped", tvQtyScrapped.getText());
                data.put("ScrappedCheckResult", spinnerScrappedCheckResult.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("ScrappedConservationMeasure", spinnerScrappedConservationMeasure.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("ScrappedQAState", spinnerScrappedQAState.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("ScrappedRecommendations", spinnerScrappedRecommendations.<Statu>getItems().get(spinnerConservationMeasure.getSelectedIndex()).getId());
                data.put("Description", tvDescription.getText());
                mPresenter.doConfirm(data, () -> {
                    showMessage("操作成功！");
                    setFragmentResult(RESULT_OK,null);
                    pop();
                });
                break;
        }
    }


    /**
     * 显示错误提示，并获取焦点
     *
     * @param textInputLayout
     * @param error
     */
    private void showError(TextInputLayout textInputLayout, String error) {
        textInputLayout.setError(error);
        textInputLayout.getEditText().setFocusable(true);
        textInputLayout.getEditText().setFocusableInTouchMode(true);
        textInputLayout.getEditText().requestFocus();
    }


    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();
        tvQtyScrapped.setText(String.valueOf(mMaintainBean.getQtyScrapped()));
        tvConservationDate.setText(TimeDialogUtil.getBeforeMonth(0));
        tvCheckQty.setText("");

    }

    private class MyTextWatcher implements TextWatcher {
        TextInputLayout mTextInputLayout;
        String message;

        public MyTextWatcher(TextInputLayout textInputLayout, String msg) {
            mTextInputLayout = textInputLayout;
            message = msg;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s)) {
                count++;
                showError(mTextInputLayout, message);
            } else if (mTextInputLayout.isErrorEnabled()) {
                count--;
                mTextInputLayout.setErrorEnabled(false);
            }
            if (count == 0) {
                btMaintainDetailOk.setEnabled(true);
            } else {
                btMaintainDetailOk.setEnabled(false);
            }
        }
    }
}
